package com.jy.api.service.impl;

import com.jy.api.dao.MaterialDao;
import com.jy.api.domain.Material;
import com.jy.api.service.MaterialService;
import com.jy.api.signUpReq.admin.MaterialSignUpReq;
import com.jy.api.util.PinYinUtil;
import com.jy.api.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by lihu on 2017/11/11.
 */
@Service
public class MaterialServiceImpl implements MaterialService {

    @Autowired
    MaterialDao materialDao;

    @Override
    @Transactional
    public void addMaterial(MaterialSignUpReq materialSignUpReq) {
        Material material = materialDao.findByStoreIdAndNameAndEnabled(materialSignUpReq.getStoreId(),
                materialSignUpReq.getName(), true);
        if (material == null) {
            material = new Material(UuidUtil.getUuid(), materialSignUpReq.getStoreId(), materialSignUpReq.getName(),
                    PinYinUtil.getFirstSpell(materialSignUpReq.getName()));
            materialDao.save(material);
        }

    }

    @Override
    public Page<Material> getMaterial(String storeId, Pageable pageable) {
        Page<Material> materials = materialDao.findByStoreId(storeId, pageable);
        return materials;
    }

    @Override
    public List<Material> searchCode(String storeId, String searchCode, Pageable pageable) {
        Page<Material> materials = materialDao.findByStoreIdAndSearchCodeLike(storeId, searchCode, pageable);
        return materials.getContent();
    }
}
